package com.simafei.flow.web.util;

import cn.hutool.core.collection.CollectionUtil;
import com.simafei.flow.core.json.JsonUtils;
import com.simafei.flow.web.common.error.BizErrorCode;
import com.simafei.flow.web.common.error.BizException;
import com.simafei.flow.web.domain.req.VariableReq;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class VariableUtils {

    public static void checkDuplicateVarNames(List<VariableReq> variables) {
        List<String> varNames = duplicateVarNames(variables);
        if (CollectionUtil.isNotEmpty(varNames)) {
            throw new BizException(BizErrorCode.DUPLICATE_VAR_NAMES, JsonUtils.toJsonString(varNames));
        }
    }

    public static List<String> duplicateVarNames(List<VariableReq> variables) {
        Map<String, Integer> nameCountMap = variables.stream()
                .collect(Collectors.groupingBy(
                        VariableReq::getVarName,
                        Collectors.summingInt(v -> 1)
                ));

        return nameCountMap.entrySet().stream()
                .filter(entry -> entry.getValue() > 1)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
    }
}
